package cn.yunhe.springmvc.locate.controller;

import java.util.Locale;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

/**
 * 定制SpringMVC的配置（如：日期、语言等） 有点类似于Spring的XML的文件配置 可以添加需要用的Bean,还有拦截器、事务控制等
 * 
 */
@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {

	/**
	 * 格式转换处理
	 * 
	 * @param registry
	 */
	@Override
	public void addFormatters(FormatterRegistry registry) {
		// registry.addFormatterForFieldType(LocalDate.class, new
		// USLocalDateFormatter());
	}

	/**
	 * 从HTTP的请求地址中找到所属于的国家
	 * 
	 * @return
	 */
	@Bean(name="localeResolver")
	public LocaleResolver localeResolver() {
		SessionLocaleResolver localeResolver=new SessionLocaleResolver();
		//localeResolver.setDefaultLocale(Locale.ENGLISH);//对应英国messages_en.properties
		//localeResolver.setDefaultLocale(Locale.US);//对应美国messages_en_US.properties
		//localeResolver.setDefaultLocale(Locale.CHINA);//对应中国messages_en_US.properties
		localeResolver.setDefaultLocale(new Locale("en", "US"));
		return localeResolver;
	}

	/**
	 * 国际化
	 * 
	 * @return
	 */
	@Bean(name="messageSource")
	public ResourceBundleMessageSource messageSource() {
		ResourceBundleMessageSource bundleMessageSource = new ResourceBundleMessageSource();
		bundleMessageSource.setDefaultEncoding("UTF-8");
		bundleMessageSource.setBasename("lang.messages");
		bundleMessageSource.setUseCodeAsDefaultMessage(true);
		return bundleMessageSource;
	}

	/**
	 * 拦截器：拦截请求的地址
	 * 
	 * @return
	 */
	@Bean
	public LocaleChangeInterceptor localeChangeInterceptor() {
		LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
		// 在拦截的地址后面添加？lang=xx。如： http://localhost:8080/profile?lang=fr
		//localeChangeInterceptor.setParamName("lang");
		return localeChangeInterceptor;
	}

	/**
	 * 注册拦截器
	 * 
	 * @param registry
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(localeChangeInterceptor());
	}
}
